package com.ck.controller.teacher;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ck.domain.Banji;
import com.ck.service.TeacherService;

public class AddNewBanjiController extends SimpleFormController {
	
	private TeacherService teacherService;

	public void setTeacherService(TeacherService teacherService) {
		this.teacherService = teacherService;
	}
	
	protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {
		
		Banji banji = (Banji) command;
		Map model = errors.getModel();
		
		//后台校验
		boolean flag = true;
		String name = banji.getName().trim();
		String remark = banji.getRemark().trim();
		
		if(name == null || "".equals(name)) {
			model.put("error_name", "请输入班级名称");
			flag = false;
		}
		
		if(name.length() > 30) {
			model.put("error_name", "名称长度：1-30个字符");
			flag = false;
		}
		
		if( remark == null || "".equals(remark) ){
        	banji.setRemark(null);
        }else{
        	if(remark.length() > 60) {
    			model.put("error_remark", "备注长度：0-60个字符");
    			flag = false;
    		}
        }
		
		//校验不通过
        if(!flag){
        	model.put("name", name);
        	model.put("remark", remark);
			return new ModelAndView(getFormView(), model);
		}
		
		boolean isNewBanji = teacherService.addNewBanji(banji, model);
		
		if (isNewBanji) {
            return new ModelAndView(getSuccessView(),model);
        } else {
        	model.put("name", name);
        	model.put("remark", remark);
            return new ModelAndView(getFormView(), model);
        }
	}

}
